<?php

/**
 * 后台控制器基类
 * File Name：AdminBase.php
 */
class AdminBase extends YzwController {

    //不使用布局
    public $layout = false;
    //当前登录用户uid
    public static $uid = 0;
    //当前登录用户会员名称
    public static $username = NULL;
    //当前登录会员详细信息
    public static $userInfo = array();
    //模板输出变量
    protected $tVar = array(
        //默认提示跳转时间
        'waitSecond' => 2000,
    );

    //初始化
    public function init() {
        parent::init();
        //快捷模板变量
        $this->assign('staticUrl', Yii::app()->params->staticUrl);
        //权限检查
        $this->competence();
    }

    /**
     * RBAC权限检测
     * init初始的时候已经判断是否有登录了，这里不再需要判断
     * @param type $action
     * @return boolean
     */
    public function runAction($action) {
        //RBAC
        if (!RBAC::AccessDecision(GROUP_NAME)) {
            //检查认证识别号
            if (!RBAC::checkLogin()) {
                //跳转到登录页面
                $this->redirect(array('public/login'));
                return false;
            }
            $this->error('对不起，您没有该项操作的权限！');
        } else {
            parent::runAction($action);
        }
    }

    /**
     * 验证登录
     * @return boolean
     */
    private function competence() {
        //检查是否登录
        self::$uid = Yii::app()->passport->isLogin();
        if (empty(self::$uid)) {
            //一些特殊的控制器，不用要求登录
            if (in_array(strtolower($this->getId()), explode(',', NOT_AUTH_CONTROLLER))) {
                return true;
            }
            //跳转到登录页面
            $this->redirect(array('public/login'));
            return false;
        }
        //获取当前登录用户信息
        self::$userInfo = Yii::app()->passport->getLocalAdminUser(self::$uid);
        if (empty(self::$userInfo)) {
            Yii::app()->passport->logoutLocal();
            return false;
        }
        //是否锁定
        if (!self::$userInfo['status']) {
            Yii::app()->passport->logoutLocal();
            $this->error('您的帐号已经被锁定！', self::U('public/login'));
            return false;
        }
        self::$username = self::$userInfo['admin_name'];
        return self::$userInfo;
    }


    protected function dispatchJump($message, $status = 1, $jumpUrl = '', $ajax = false) {
        //记录日志
        AdminOperationLog::model()->record($message, $status);
        parent::dispatchJump($message, $status, $jumpUrl, $ajax);
    }

    /**
     * 验证码验证
     * @param type $verifyCode 验证码
     * @return boolean 正确true，不正确false
     */
    protected function validateVerifyCode($verifyCode) {
        if (empty($verifyCode)) {
            return false;
        }
        //验证验证码输入
        $valid = $this->createAction('captcha')->validate($verifyCode, false);
        return $valid ? true : false;
    }


    /**
     * 基础信息列表方法
     * @param type $model 模型对象或者模型名
     * @param type $where 条件表达式
     * @param type $limit 每次显示多少
     */
    protected function basePage($model, $where = array(), $limit = 20) {
        $model = new $model('search');
        //分页
        $pageId = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $criteria = is_object($where) ? $where : $model->where($where);
        //信息总数
        $count = $model->count($criteria);
        //分页
        $page = self::page($count, $limit, $pageId);
        //查询信息
        $criteria->limit = $page->listRows;
        $criteria->offset = $page->firstRow;
        $data = $model->findAll($criteria);

        $this->assign("Page", $page->show());
        $this->assign('data', $data);
        $this->assign('count', $count);
    }

    /**
     * basePage是兼容原来的写法，以后的换成这种更具体的
     * 后台基本的列表展示控制器
     * @param  [type]  $model [description]
     * @param  array   $params [提供的额外的参数]
     * @param  integer $limit [description]
     * @return [type]         [description]
     */
    protected function baseIndex($model, $params = array(), $limit = 20){
        $objModel = new $model('search');
        $objModel->unsetAttributes();
        if(isset($_GET[$model]))
        {
            $objModel->attributes = $_GET[$model];
        }
        $objCriteria = $objModel->createSearchCriteria();
        if($params){
            foreach($params as $key => $value){
                if(is_numeric($key)){
                   $objCriteria->addCondition($value); 
                }else{
                    $objCriteria->$key = $value;
                }
            }
        }        
        //分页
        $pageId = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        //信息总数
        $count = $objModel->count($objCriteria);
        //分页
        $page = self::page($count, $limit, $pageId,'',$objCriteria);
        $data = $model->findAll($objCriteria);

        $this->assign("Page", $page->show());
        $this->assign('data', $data);
        $this->assign('model', $objModel);
        $this->assign('count', $count);        
    }


    /**因为后台的单个的增加/修改/删除的都是ajax的方式处理，POST数据后逻辑肯定是跳转。
     * 基础Add简洁方法
     * @param type $model  模型对象或者模型名
     * @param type $url
     */
    protected function baseAdd($model, $url = 'index') {
        $objModel = new $model('admin');
        $objModel->unsetAttributes();
        if (IS_POST) {
            if(!empty($_POST[$model])){
                $objModel->attributes = $_POST;                
            }else{
                $objModel->attributes = $_POST[$model]; 
            }
            if ($objModel->save()) {
                $this->success('添加成功！', self::U($url));
            } else {
                $error = $objModel->getOneError();
                $this->error($error ? $error : '添加失败！');
            }
        }
        $this->assign('data', $objModel);
        $this->render();
    }

    /**
     * 基础信息编辑
     * @param model $model 模型对象或者模型名
     * @param type $url
     */
    protected function baseEdit($model, $url = 'index') {
        $objModel = new $model('admin');
        $id = Yii::app()->request->getParam($objModel->getTableSchema()->primaryKey);
        $objModel = $objModel->findByPk($id);
        if (empty($objModel)) {
            $this->error('该信息不存在！');
        }
        if (IS_POST) {
            if(!empty($_POST[$model])){
                $objModel->attributes = $_POST;                
            }else{
                $objModel->attributes = $_POST[$model]; 
            }
            if ($objModel->save()) {
                $this->success('修改成功！', self::U($url));
            } else {
                $error = $data->getOneError();
                $this->error($error ? $error : '修改失败！');
            }
        }

        $this->assign('data', $objModel);
        $this->render();
    }

    /**
     * 基本信息删除
     * @param model $model 模型对象或者模型名
     * @param type $url
     */
    protected function baseDelete($model, $url = 'index') {
        $objModel = new $model('admin');
        $id = Yii::app()->request->getParam($objModel->getTableSchema()->primaryKey);
        $objModel = $objModel->findByPk($id);
        if (empty($objModel)) {
            $this->error('该信息不存在！');
        }
        if ($objModel>delete()) {
            $this->success('删除成功！', self::U($url));
        } else {
            $this->error('删除失败！');
        }
    }

}
